import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class templateDem0 {
    public  static JdbcTemplate template ;

    static {
        try {
            template =  new JdbcTemplate(createDataSource());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改操作
     */
    @Test
    public void test1 () {
        String sql = "update student set name = ? where id = 1";
        int count = template.update(sql, "han");
        System.out.println(count);
    }

    /**
     * 新增操作
     */
    @Test
    public void test2 () {
        String sql = "insert into student values (? ,?)";
        template.update(sql , 5 , "susan");
        template.update(sql , 6  , "shui");
    }

    /**
     * 删除操作
     */
    @Test
    public void test3() {
        String sql = "delete from student where id = ?";
        int count = template.update(sql, 5);
        System.out.println(count);
    }

    /**
     * 查询
     */
    @Test
    public void test4() {
        String sql = "select * from student where id = 1";
        Map<String, Object> stringObjectMap = template.queryForMap(sql);
        System.out.println(stringObjectMap);
    }

    @Test
    public void test5 () {
        String sql = "select * from student";
        List<Map<String, Object>> maps = template.queryForList(sql);
        System.out.println(maps);
    }

    @Test
    public void test7 () {
        String sql = "select count(id) from student";
        Long aLong = template.queryForObject(sql, Long.class);
        System.out.println(aLong);
    }

    @Test
    public void test6() {
        String sql = "select * from student";
        List<Student> query = template.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        System.out.println(query);
    }

    public static DataSource createDataSource () throws Exception {
        Properties properties = new Properties();
        InputStream resourceAsStream = Template.class.getResourceAsStream("druid/druid-config.properties");

        properties.load(resourceAsStream);
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        return dataSource;
    }
}
